<template>
  <div>
    <categroy :scene="scene" />
    <el-card style="margin-top: 20px;">
      <div v-if="!scene">
        <el-button type="primary" :disabled="!categroyStore.c3Id" icon="plus" @click="addAttr">添加平台属性</el-button>
        <vue-table style="margin: 10px 0;" @confirmDelete="confirmDelete1" @operation="operation" :loading="tableLoading" :pageInfo="pageInfo" :tableHeade="tableHeade" :tableData="tableData" :operationList="operationList" :border="true">
          <template #default="{ row, head }">
            <div v-if="head==='attrValueList'">
              <el-tag style="margin: 0 2px;" v-for="item in row.attrValueList" :key="item.id">{{ item.valueName }}</el-tag>
            </div>
          </template>
        </vue-table>
      </div>
      <div v-else>
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrData.attrName" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <el-button type="primary" :disabled="!attrData.attrName" icon="plus" @click="addAttrValue">添加属性值</el-button>
        <el-button>取消</el-button>
        <vue-table style="margin: 10px 0;" @confirmDelete="confirmDelete" :tableHeade="tableHeadeAttr" :tableData="attrData.attrValueList" :operationList="operationListAttr">
          <template #default="{ row, head, $index }">
            <div v-if="head==='valueName'">
              <el-input :ref="(vc:any) => inputArr[$index]=vc" v-if="row.isEdit" :autofocus="row.isEdit" @blur="toLook(row, $index)" v-model="row.valueName" />
              <div v-else @click="toEdit(row, $index)">{{row.valueName}}</div>
            </div>
          </template>
        </vue-table>
        <el-button type="primary" :disabled="attrData.attrValueList.length < 1 || !attrData.attrName" @click="save" v-bind:loading="btnLoading">保存</el-button>
        <el-button @click="cancel" v-bind:loading="btnLoading">取消</el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
  import useCategoryStore from '@/store/modules/category'
  import { watch } from 'vue'
  import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr'
  import type { AttrResponsData, Attr, AttrValue } from '@/api/product/attr/type'
  import type { operationListType, tableDataType } from '@/components/Table/type'
  import { ElMessage } from 'element-plus'

  let categroyStore = useCategoryStore()
  let tableLoading = ref(false)
  let tableData = reactive<Attr[]>([])
  watch(()=> categroyStore.c3Id, async () => {
    getAttr()
  })
  let inputArr = reactive<any>([])
  onBeforeUnmount(() => {
    categroyStore.$reset()
  })
  let scene = ref<number>(0)
  let attrData = reactive<Attr>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3
  })
  const toEdit = (item: AttrValue, $index: number) => {
    item.isEdit = true
    nextTick(() => {
      inputArr[$index].focus()
    })
    
  }
  const toLook = (item: AttrValue, $index: number) => {
    if (!item.valueName) {
      ElMessage({ message: '属性值不能为空！', type: 'error' })
      attrData.attrValueList.splice($index, 1)
      return
    }
    let repeat = attrData.attrValueList.find((i) => {
      if (i!==item) {
        return item.valueName === i.valueName
      }
    })
    if (repeat) {
      ElMessage({ message: '属性值不能重复！', type: 'error' })
      attrData.attrValueList.splice($index, 1)
      return
    }
    item.isEdit = false
  }
  const getAttr = async () => {
    const { c1Id, c2Id, c3Id } = categroyStore
    if (!c3Id) return tableData = []
    tableLoading.value = true
    let res: AttrResponsData = await reqAttr(c1Id, c2Id, c3Id)
    if (res.code === 200) {
      tableData = res.data
    }
    tableLoading.value = false
  }
  const addAttrValue = () => {
    let obj = {
      valueName: '',
      isEdit: true,
      attrId: attrData.id ? attrData.id : ''
    }
    attrData.attrValueList.push(obj)
    nextTick(() => {
      inputArr[inputArr.length - 1].focus()
    })
  }
  const addAttr = () => {
    Object.assign(attrData, {
      attrName: '',
      attrValueList: [],
      categoryId: '',
      categoryLevel: 3
    })
    scene.value = 1
    attrData.categoryId = categroyStore.c3Id
  }
  const editAttr = (obj: Attr) => {
    let copyObj = JSON.parse(JSON.stringify(obj))
    Object.assign(attrData, copyObj)
    scene.value = 1
  }
  const btnLoading = ref(false)
  const save = async () => {
    btnLoading.value = true
    let res:any = await reqAddOrUpdateAttr(attrData)
    if (res.code === 200) {
      scene.value = 0
      getAttr()
      ElMessage({ message: '操作成功！', type: 'success' })
    }
    btnLoading.value = false
  }
  const cancel = () => {
    scene.value = 0
  }
  const operation = (item: operationListType, obj: Attr) => {
    if (item.index === 1) editAttr(obj)
  }
  const confirmDelete = (e: tableDataType, index: number) => {
    attrData.attrValueList.splice(index, 1)
  }
  const confirmDelete1 = async (e: tableDataType) => {
    let res:any = await reqDeleteAttr(e.id)
    if (res.code === 200) {
      getAttr()
      ElMessage({ message: '操作成功！', type: 'success' })
    } else {
      ElMessage({ message: '操作失败！', type: 'error' })
    }
  }
  let pageInfo = reactive({
    page: 1,
    total: 0,
    limit: 10
  })
  const tableHeade = reactive([
    { prop: 'attrName', label: '属性名称', width: '250'},
    { prop: 'attrValueList', label: '属性值名称', custom: true},
  ])
  const tableHeadeAttr = reactive([
    { prop: 'valueName', label: '属性名值称', custom: true},
  ])
  const operationList = reactive([
    { name: '编辑', index: 1, isShow: true},
    { name: '删除', index: 2, color: 'red', isShow: true}
  ])
  const operationListAttr = reactive([
    { name: '删除', index: 1, color: 'red', isShow: true}
  ])
</script>
<style scoped lang="scss">
</style>
